<script setup>
import {onMounted, ref, reactive, computed} from 'vue';
import {useUserStore} from '@/stores/user';
import {useNotificationStore} from '@/stores/notification';
import Request from '@/utils/Request';

// 导入图表子组件
import CaloriesChart from '@/components/charts/CaloriesChart.vue';
import WeightChart from '@/components/charts/WeightChart.vue';
import WaterChart from '@/components/charts/WaterChart.vue';
import SleepChart from '@/components/charts/SleepChart.vue';

// --- 状态管理 ---
const userStore = useUserStore();
const notificationStore = useNotificationStore();
const loading = ref(true);
const dashboardData = ref(null);

// --- 快速记录（增加）弹窗状态 ---
const recordDialog = reactive({
  show: false,
  type: 'weight', // weight | water | sleep
  value: null,
  isSaving: false,
});

// --- 【新增】编辑总睡眠弹窗状态 ---
const editSleepDialog = reactive({
  show: false,
  value: null,
  date: null, // 需要知道编辑的是哪一天
  isSaving: false,
});


// --- 计算属性：判断仪表盘是否为空 ---
const isEmpty = computed(() => {
  if (!dashboardData.value) return true;
  const {weightTrend, waterIntakeTrend, sleepTrend, caloriesInTrend} = dashboardData.value;
  const hasData =
      (weightTrend && weightTrend.length > 0) ||
      (waterIntakeTrend && waterIntakeTrend.some(d => d.value > 0)) ||
      (sleepTrend && sleepTrend.some(d => d.value > 0)) ||
      (caloriesInTrend && caloriesInTrend.some(d => d.value > 0));
  return !hasData;
});

// --- 加载仪表盘数据 ---
const fetchDashboardData = () => {
  loading.value = true;
  Request.get('/dashboard', {days: 7})
      .then(response => {
        dashboardData.value = response.data;
      })
      .catch(error => {
        console.error('加载仪表盘数据失败:', error);
        notificationStore.error('加载仪表盘数据失败');
      })
      .finally(() => {
        loading.value = false;
      });
};

// --- 打开记录（增加）对话框 ---
const openRecordDialog = (type) => {
  recordDialog.type = type;
  recordDialog.value = null;
  recordDialog.isSaving = false;
  recordDialog.show = true;
};

// --- 【新增】打开编辑睡眠对话框 ---
// 这个方法需要由 SleepChart.vue 的 'edit' 事件触发
const openEditSleepDialog = (data) => {
  // 假设子组件会传来 { date: 'YYYY-MM-DD', value: 123 }
  // 如果没传来当天日期，则安全获取
  if (!data.date) {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    editSleepDialog.date = `${year}-${month}-${day}`;
  } else {
    editSleepDialog.date = data.date;
  }

  editSleepDialog.value = data.value;
  editSleepDialog.isSaving = false;
  editSleepDialog.show = true;
};


// --- 处理快速记录（增加/覆盖）的逻辑 ---
const handleQuickRecord = () => {
  if (!recordDialog.value || recordDialog.value <= 0) {
    notificationStore.warning('请输入一个有效的正数');
    return;
  }

  recordDialog.isSaving = true;

  // --- 【关键修改】修复时区 Bug ---
  // 安全地获取用户本地的 YYYY-MM-DD 格式日期
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const localToday = `${year}-${month}-${day}`;

  let url = '';
  let payload = {};

  // 根据类型构建 API 请求
  switch (recordDialog.type) {
    case 'weight':
      url = '/daily-logs/weight'; // POST - 覆盖逻辑
      payload = {weightKg: recordDialog.value, date: localToday};
      break;
    case 'water':
      url = '/daily-logs/water-intake'; // POST - 累加逻辑
      payload = {milliliters: recordDialog.value, date: localToday};
      break;
    case 'sleep':
      url = '/daily-logs/sleep'; // POST - 累加逻辑
      payload = {minutes: recordDialog.value, date: localToday};
      break;
  }

  Request.post(url, payload)
      .then(() => {
        notificationStore.success(`记录成功！`);
        recordDialog.show = false;
        fetchDashboardData(); // 成功后刷新数据
      })
      .catch(error => {
        console.error('快速记录失败:', error);
        notificationStore.error('记录失败，请稍后再试');
      })
      .finally(() => {
        recordDialog.isSaving = false;
      });
};

// --- 【新增】处理更新总睡眠的逻辑 ---
const handleUpdateSleep = () => {
  if (editSleepDialog.value === null || editSleepDialog.value < 0) {
    notificationStore.warning('请输入一个有效的睡眠时长');
    return;
  }

  editSleepDialog.isSaving = true;

  const payload = {
    totalMinutes: editSleepDialog.value,
    date: editSleepDialog.date
  };

  // 调用新的 PUT 接口，实现覆盖逻辑
  Request.put('/daily-logs/sleep', payload)
      .then(() => {
        notificationStore.success('总睡眠时长更新成功！');
        editSleepDialog.show = false;
        fetchDashboardData(); // 刷新图表
      })
      .catch(error => {
        console.error('更新总睡眠失败:', error);
        notificationStore.error('更新失败，请稍后再试');
      })
      .finally(() => {
        editSleepDialog.isSaving = false;
      });
};


// --- 生命周期钩子 ---
onMounted(() => {
  if (!userStore.userProfile) {
    userStore.fetchUserProfile();
  }
  fetchDashboardData();
});
</script>

<template>
  <div>
    <!-- 用户信息卡片 -->
    <v-card v-if="userStore.userProfile" class="pa-4 mb-6">
      <v-card-title class="d-flex justify-space-between align-center">
        <span class="text-h4">欢迎回来...</span>
        <div class="d-flex" style="gap: 8px;">
          <v-btn color="primary" variant="elevated" @click="openRecordDialog('weight')">
            <v-icon left>mdi-scale-bathroom</v-icon>
            记录体重
          </v-btn>
          <v-btn color="teal-darken-1" variant="outlined" @click="openRecordDialog('water')">
            <v-icon left>mdi-cup-water</v-icon>
            <!-- 【UI修改】明确意图 -->
            增加饮水
          </v-btn>
          <v-btn color="deep-purple-accent-3" variant="outlined" @click="openRecordDialog('sleep')">
            <v-icon left>mdi-sleep</v-icon>
            <!-- 【UI修改】明确意图 -->
            增加睡眠
          </v-btn>
        </div>
      </v-card-title>
      <v-card-subtitle>今天也是元气满满的一天！</v-card-subtitle>
    </v-card>

    <!-- 加载状态 -->
    <div v-if="loading" class="text-center py-10">
      <v-progress-circular indeterminate color="primary" size="64"/>
      <p class="mt-4 text-grey">正在加载您的健康数据...</p>
    </div>

    <!-- 空状态引导 -->
    <v-card v-else-if="isEmpty" class="text-center pa-8 empty-state-card">
      <v-icon size="80" color="grey-lighten-2">mdi-chart-bar-off</v-icon>
      <h2 class="text-h5 mt-6">你的健康仪表盘还是空的</h2>
      <p class="mt-2 text-grey-darken-1">
        开始记录你的第一笔健康数据，让我们一起见证你的改变！
      </p>
      <div class="mt-8">
        <v-btn color="primary" size="large" class="ma-2" to="/nutrition">
          <v-icon left>mdi-camera</v-icon>
          记录第一餐
        </v-btn>
        <v-btn color="secondary" size="large" class="ma-2" @click="openRecordDialog('weight')">
          <v-icon left>mdi-weight-kilogram</v-icon>
          记录今日体重
        </v-btn>
        <v-btn color="teal" size="large" class="ma-2" @click="openRecordDialog('water')">
          <v-icon left>mdi-cup-water</v-icon>
          增加今日饮水
        </v-btn>
        <v-btn color="deep-purple-accent-3" size="large" class="ma-2" @click="openRecordDialog('sleep')">
          <v-icon left>mdi-sleep</v-icon>
          增加今日睡眠
        </v-btn>
      </div>
    </v-card>

    <!-- 正常图表区域 -->
    <v-row v-else-if="dashboardData">
      <v-col cols="12">
        <v-card variant="outlined">
          <v-card-title>热量平衡 (大卡)</v-card-title>
          <v-card-text>
            <CaloriesChart
                :calories-in-trend="dashboardData.caloriesInTrend"
                :calories-out-trend="dashboardData.caloriesOutTrend"
            />
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" md="6">
        <v-card variant="outlined">
          <v-card-title>体重趋势 (kg)</v-card-title>
          <v-card-text>
            <WeightChart
                :trend-data="dashboardData.weightTrend"

                :target-weight="dashboardData.targets?.targetWeightKg"
            />
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" md="6">
        <v-card variant="outlined">
          <v-card-title>饮水记录 (ml)</v-card-title>
          <v-card-text>
            <WaterChart
                :trend-data="dashboardData.waterIntakeTrend"

                :recommended-intake="dashboardData.targets?.recommendedWaterInMl"
            />
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12">
        <SleepChart
            :trend-data="dashboardData.sleepTrend"
            @edit="openEditSleepDialog"

            :recommended-range="[
                dashboardData.targets?.recommendedSleepMinutesMin,
                dashboardData.targets?.recommendedSleepMinutesMax
              ]"
        />
      </v-col>
    </v-row>

    <!-- 快速记录（增加/覆盖）对话框 -->
    <v-dialog v-model="recordDialog.show" max-width="400px">
      <v-card>
        <v-card-title>
          <!-- 【UI修改】明确弹窗意图 -->
          {{
            recordDialog.type === 'weight'
                ? '记录体重'
                : recordDialog.type === 'water'
                    ? '增加饮水记录'
                    : '增加睡眠记录'
          }}
        </v-card-title>
        <v-card-text>
          <v-text-field
              v-model="recordDialog.value"
              :label="
              recordDialog.type === 'weight'
                ? '体重 (kg)'
                : recordDialog.type === 'water'
                ? '本次饮水量 (ml)'
                : '本次睡眠时长 (分钟)'
            "
              type="number"
              variant="outlined"
              clearable
          ></v-text-field>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn text @click="recordDialog.show = false">取消</v-btn>
          <v-btn color="primary" :loading="recordDialog.isSaving" @click="handleQuickRecord">
            保存
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 【新增】编辑总睡眠的对话框 -->
    <v-dialog v-model="editSleepDialog.show" max-width="400px">
      <v-card>
        <v-card-title>
          编辑总睡眠时长
        </v-card-title>
        <v-card-text>
          <p class="text-caption mb-2">正在编辑日期: {{ editSleepDialog.date }}</p>
          <v-text-field
              v-model="editSleepDialog.value"
              label="新的总睡眠时长 (分钟)"
              type="number"
              variant="outlined"
              clearable
              autofocus
          ></v-text-field>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn text @click="editSleepDialog.show = false">取消</v-btn>
          <v-btn color="primary" :loading="editSleepDialog.isSaving" @click="handleUpdateSleep">
            保存更新
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </div>
</template>

<style scoped>
.empty-state-card {
  border: 2px dashed #e0e0e0;
  transition: background-color 0.3s ease;
}

.empty-state-card:hover {
  background-color: #fafafa;
}
</style>